//
//  AllBaseViewController.m
//  yunqiphone
//
//  Created by Maple on 13-5-16.
//  Copyright (c) 2013年 ci123.com. All rights reserved.
//

#import "AllBaseViewController.h"
#import "MBProgressHUD.h"
#import "OLImageView.h"
#import "OLImage.h"
#import "UIImage+fixOrientation.h"

@interface AllBaseViewController ()

@end

@implementation AllBaseViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _canBack = YES;
        _isWebview = NO;
        _isHome = NO;
        _isTarView = NO;
        if (Current_device_vesion >= 7.0) {
            if ([self respondsToSelector:@selector(automaticallyAdjustsScrollViewInsets)]){
                self.automaticallyAdjustsScrollViewInsets = NO;
            }
        }
    }
    return self;
}

- (void)loadView {

    UIView *view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    view.backgroundColor = DefaultViewBackgroundColor;
    self.view = view;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    WS(weakSelf);
    //自定义导航
    _nav = [UIView new];
    _nav.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_nav];
    
    [_nav mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(weakSelf.view).insets(UIEdgeInsetsMake(0, 0, 0, 0));
        make.height.equalTo(NavHeight);
    }];
    
    _navBackView = [UIView new];
    _navBackView.backgroundColor = [UIUtils getColorByString:AppStyleConfig[appUserType][@"navColor"]];
    [_nav addSubview:_navBackView];
    
    [_navBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_nav).insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    _navTitle = [UILabel new];
    _navTitle.backgroundColor = [UIColor clearColor];
    _navTitle.textAlignment = NSTextAlignmentCenter;
    _navTitle.adjustsFontSizeToFitWidth = YES;
    _navTitle.font = [UIFont boldSystemFontOfSize:20];
    _navTitle.text = self.title;
    _navTitle.textColor = [UIColor whiteColor];
    [_nav addSubview:_navTitle];
    
    [_navTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(_nav).insets(UIEdgeInsetsMake(Status_Gap, 55, 0, 55));
        make.height.equalTo(NavHeight - Status_Gap);
    }];
    
    if(_canBack){
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, Status_Gap , 44, 44)];
        button.showsTouchWhenHighlighted = YES;
        button.backgroundColor = [UIColor clearColor];
        button.imageEdgeInsets = UIEdgeInsetsMake(0, 8, 0, 0);
        [button setImage:[UIImage imageNamed:@"nav_btn_back"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(backPage:) forControlEvents:UIControlEventTouchUpInside];
        [_nav addSubview:button];
    }
    
    [self _iniView];
}

- (void)viewWillDisappear:(BOOL)animated
{

    [super viewWillDisappear:animated];
   
    
    [NOTIFICATION_CENTER removeObserver:self name:kNetworkStateChangedNotification object:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self showBaseBackgroundTip];
    if (!_isTarView) {
        [self setHidesBottomBarWhenPushed:YES];
    }
    [self.view bringSubviewToFront:_nav];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
}

// 支持设备自动旋转
- (BOOL)shouldAutorotate {
    
    return YES;
}

// 支持横竖屏显示
- (NSUInteger)supportedInterfaceOrientations {
    
    return UIInterfaceOrientationMaskPortrait;
}

#pragma mark - UI

- (void)_iniView {
    
    if (_isHome) {
        _navBackView.alpha = 0.0f;
    }
    
    if(!_loadingView && _isWebview){
        
        WS(weakSelf);
        CGFloat length = 205.0f;
        
        _loadingView = [[UIView alloc]init];
        _loadingView.backgroundColor = DefaultViewBackgroundColor;
        [self.view addSubview:_loadingView];
        [_loadingView setHidden:YES];
        
        [_loadingView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(weakSelf.view).insets(UIEdgeInsetsMake(NavHeight, 0, 0, 0));
        }];
        
        OLImageView *loadingImageView = [OLImageView new];
        [loadingImageView setHidden:YES];
        [loadingImageView setBackgroundColor:[UIColor clearColor]];
        [loadingImageView setTag:BaseBackgroundTipTypeLoading];
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"base_loading" ofType:@"gif"];
        NSData *gifData = [NSData dataWithContentsOfFile:filePath];
        loadingImageView.image = [OLImage imageWithData:gifData];
        [_loadingView addSubview:loadingImageView];
        
        [loadingImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(_loadingView.mas_centerX);
            make.centerY.equalTo(_loadingView.mas_centerY).offset(-50);
            make.width.equalTo(length);
            make.height.equalTo(length);
        }];
        
        UIImageView *noNetImageView = [[UIImageView alloc]init];
        [noNetImageView setTag:BaseBackgroundTipTypeNoNet];
        [noNetImageView setHidden:YES];
        [noNetImageView setImage:[UIImage imageNamed:@"base_nonet"]];
        [noNetImageView setBackgroundColor:[UIColor clearColor]];
        [_loadingView addSubview:noNetImageView];

        [noNetImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(_loadingView.mas_centerX);
            make.centerY.equalTo(_loadingView.mas_centerY).offset(-50);
            make.width.equalTo(length);
            make.height.equalTo(length);
        }];
    }
    
    [NOTIFICATION_CENTER addObserver:self
                            selector:@selector(showBaseBackgroundTip)
                                name:kNetworkStateChangedNotification
                              object:nil];
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

#pragma mark - MBHud
- (void)showHud:(NSString *)title isDim:(BOOL)isDim {
    _hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    _hud.dimBackground = isDim;
    if(title.length > 0) {
        _hud.labelText = title;
    }
}

- (void)showHudComplete:(NSString *)title success:(BOOL)success {
  NSString *name = success ? @"success" : @"excla";
  _hud.dimBackground = NO;
  _hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:name]];
  _hud.mode = MBProgressHUDModeCustomView;
  if(title.length > 0) {
    _hud.labelText = title;
  }
    NSTimeInterval seconds=success ? 1 : 2;
    
  [_hud hide:YES afterDelay:seconds];
}

- (void)ShowExclaHud:(NSString *)title{
  _hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
  [self showHudComplete:title success:NO];
}

- (void)hideHud {
  [_hud hide:YES];
}

- (AppDelegate *)getAppDelegate {
  AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
  return appDelegate;
}

#pragma mark - Action

- (void)showBaseBackgroundTip
{
    UIImageView *noNet = (UIImageView *)[_loadingView viewWithTag:BaseBackgroundTipTypeNoNet];
    OLImageView *loading = (OLImageView *)[_loadingView viewWithTag:BaseBackgroundTipTypeLoading];
    if (appNetworkStatus != NotReachable) {
        [noNet setHidden:YES];
        [loading setHidden:NO];
    }else {
        [loading setHidden:YES];
        [noNet setHidden:NO];
    }
}

- (void)backPage:(id)button
{
  [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - Create Nav
- (UIButton *)createNavRightButton:(NSString *)showName target:(id)target action:(SEL)action
{
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(APP_SCREEN_WIDTH-60-5, Status_Gap, 60, CUSTOM_NAV_HEIGHT)];
    float fontsize=18.0f;
    if(showName.length>2){
        fontsize=16.0f;
    }
    button.titleLabel.font = [UIFont systemFontOfSize:fontsize];
    [button setTitle:showName forState:UIControlStateNormal];
    button.showsTouchWhenHighlighted = YES;
    [button setBackgroundColor:[UIColor clearColor]];
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    [_nav addSubview:button];
    
    return button;
}

- (UIButton *)createNavRightButtonWithImage:(NSString *)imageString withFrame:(CGRect)frame target:(id)target action:(SEL)action
{
    UIButton *button = [[UIButton alloc] initWithFrame:frame];
    [button setImage:[UIImage imageNamed:imageString] forState:UIControlStateNormal];
    button.showsTouchWhenHighlighted = YES;
    [button setBackgroundColor:[UIColor clearColor]];
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    [_nav addSubview:button];
    return button;
}

- (UIView *)createNavCenterSilderWithNames:(NSArray *)names withBlock:(void (^)(NSInteger index))block
{
    NSInteger size = names.count;
    _centerNavBlock = block;
    if (size < 2) {
        return nil;
    }
    
    float cellWidth = 61.0f;
    float cellHeight = 28.0f;
    float width = cellWidth * size;
    float height = cellHeight + 2;
    if (size == 2) {
        width += 3;
    }else {
        width += 4;
    }
    
    int tag = 7000;
    UIView *backWrap = [[UIView alloc] init];
    [backWrap setBackgroundColor:[UIColor whiteColor]];
    [backWrap.layer setCornerRadius:7.0f];
    [backWrap.layer setMasksToBounds:YES];
    [backWrap setTag:tag];
    [_nav addSubview:backWrap];
    
    [backWrap mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_nav.mas_centerX);
        make.centerY.equalTo(_nav.mas_centerY).offset(Status_Gap / 2);
        make.width.equalTo(width);
        make.height.equalTo(height);
    }];

    UIButton *buttonFirst = [[UIButton alloc] initWithFrame:CGRectMake(1, 1, cellWidth, cellHeight)];
    [buttonFirst setBackgroundColor:[UIColor whiteColor]];
    [buttonFirst setTitle:names[0] forState:UIControlStateNormal];
    [buttonFirst setTitleColor:[UIUtils getColorByString:AppStyleConfig[appUserType][@"navColor"]]
                      forState:UIControlStateNormal];
    [buttonFirst setShowsTouchWhenHighlighted:YES];
    [buttonFirst setTag:++tag];
    [buttonFirst.titleLabel setFont:[UIFont systemFontOfSize:15.0f]];
    [buttonFirst addTarget:self action:@selector(centerNavClick:) forControlEvents:UIControlEventTouchUpInside];
    [backWrap addSubview:buttonFirst];
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:buttonFirst.bounds
                                                   byRoundingCorners:UIRectCornerTopLeft | UIRectCornerBottomLeft
                                                         cornerRadii:CGSizeMake(7, 7)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = buttonFirst.bounds;
    maskLayer.path = maskPath.CGPath;
    buttonFirst.layer.mask = maskLayer;
    
    if (size == 3) {
        UIButton *buttonMid = [[UIButton alloc] initWithFrame:CGRectMake(2 + cellWidth, 1, cellWidth, cellHeight)];
        [buttonMid setBackgroundColor:[UIUtils getColorByString:AppStyleConfig[appUserType][@"navColor"]]];
        [buttonMid setTitle:names[1] forState:UIControlStateNormal];
        [buttonMid setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [buttonMid setShowsTouchWhenHighlighted:YES];
        [buttonMid setTag:++tag];
        [buttonMid.titleLabel setFont:[UIFont systemFontOfSize:15.0f]];
        [buttonMid addTarget:self action:@selector(centerNavClick:) forControlEvents:UIControlEventTouchUpInside];
        [backWrap addSubview:buttonMid];
    }
    
    UIButton *buttonLast = [[UIButton alloc] initWithFrame:CGRectMake(1 + (cellWidth + 1) * (size - 1), 1, cellWidth, cellHeight)];
    [buttonLast setBackgroundColor:[UIUtils getColorByString:AppStyleConfig[appUserType][@"navColor"]]];
    [buttonLast setTitle:names[size - 1] forState:UIControlStateNormal];
    [buttonLast setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [buttonLast setShowsTouchWhenHighlighted:YES];
    [buttonLast setTag:++tag];
    [buttonLast.titleLabel setFont:[UIFont systemFontOfSize:15.0f]];
    [buttonLast addTarget:self action:@selector(centerNavClick:) forControlEvents:UIControlEventTouchUpInside];
    [backWrap addSubview:buttonLast];
    UIBezierPath *maskPath2 = [UIBezierPath bezierPathWithRoundedRect:buttonLast.bounds
                                                   byRoundingCorners:UIRectCornerTopRight | UIRectCornerBottomRight
                                                         cornerRadii:CGSizeMake(7, 7)];
    CAShapeLayer *maskLayer2 = [[CAShapeLayer alloc] init];
    maskLayer2.frame = buttonLast.bounds;
    maskLayer2.path = maskPath2.CGPath;
    buttonLast.layer.mask = maskLayer2;
    
    return backWrap;
}

- (UIView *)createNavCenterSilderWithNames:(NSArray *)names withBlock:(void (^)(NSInteger index))block isWider:(BOOL)wider
{
    NSInteger size = names.count;
    _centerNavBlock = block;
    if (size < 2) {
        return nil;
    }
    
    float cellWidth = 61.0f;
    if (wider) {
        cellWidth = 91.0f;
    }
    float cellHeight = 28.0f;
    float width = cellWidth * size;
    float height = cellHeight + 2;
    if (size == 2) {
        width += 3;
    }else {
        width += 4;
    }
    
    int tag = 7000;
    UIView *backWrap = [[UIView alloc] init];
    [backWrap setBackgroundColor:[UIColor whiteColor]];
    [backWrap.layer setCornerRadius:7.0f];
    [backWrap.layer setMasksToBounds:YES];
    [backWrap setTag:tag];
    [_nav addSubview:backWrap];
    
    [backWrap mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_nav.mas_centerX);
        make.centerY.equalTo(_nav.mas_centerY).offset(Status_Gap / 2);
        make.width.equalTo(width);
        make.height.equalTo(height);
    }];

    UIButton *buttonFirst = [[UIButton alloc] initWithFrame:CGRectMake(1, 1, cellWidth, cellHeight)];
    [buttonFirst setBackgroundColor:[UIColor whiteColor]];
    [buttonFirst setTitle:names[0] forState:UIControlStateNormal];
    [buttonFirst setTitleColor:[UIUtils getColorByString:AppStyleConfig[appUserType][@"navColor"]] forState:UIControlStateNormal];
    [buttonFirst setShowsTouchWhenHighlighted:YES];
    [buttonFirst setTag:++tag];
    [buttonFirst.titleLabel setFont:[UIFont systemFontOfSize:15.0f]];
    [buttonFirst addTarget:self action:@selector(centerNavClick:) forControlEvents:UIControlEventTouchUpInside];
    [backWrap addSubview:buttonFirst];
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:buttonFirst.bounds
                                                   byRoundingCorners:UIRectCornerTopLeft | UIRectCornerBottomLeft
                                                         cornerRadii:CGSizeMake(7, 7)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = buttonFirst.bounds;
    maskLayer.path = maskPath.CGPath;
    buttonFirst.layer.mask = maskLayer;
    
    if (size == 3) {
        UIButton *buttonMid = [[UIButton alloc] initWithFrame:CGRectMake(2 + cellWidth, 1, cellWidth, cellHeight)];
        [buttonMid setBackgroundColor:[UIUtils getColorByString:AppStyleConfig[appUserType][@"navColor"]]];
        [buttonMid setTitle:names[1] forState:UIControlStateNormal];
        [buttonMid setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [buttonMid setShowsTouchWhenHighlighted:YES];
        [buttonMid setTag:++tag];
        [buttonMid.titleLabel setFont:[UIFont systemFontOfSize:15.0f]];
        [buttonMid addTarget:self action:@selector(centerNavClick:) forControlEvents:UIControlEventTouchUpInside];
        [backWrap addSubview:buttonMid];
    }
    
    UIButton *buttonLast = [[UIButton alloc] initWithFrame:CGRectMake(1 + (cellWidth + 1) * (size - 1), 1, cellWidth, cellHeight)];
    [buttonLast setBackgroundColor:[UIUtils getColorByString:AppStyleConfig[appUserType][@"navColor"]]];
    [buttonLast setTitle:names[size - 1] forState:UIControlStateNormal];
    [buttonLast setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [buttonLast setShowsTouchWhenHighlighted:YES];
    [buttonLast setTag:++tag];
    [buttonLast.titleLabel setFont:[UIFont systemFontOfSize:15.0f]];
    [buttonLast addTarget:self action:@selector(centerNavClick:) forControlEvents:UIControlEventTouchUpInside];
    [backWrap addSubview:buttonLast];
    UIBezierPath *maskPath2 = [UIBezierPath bezierPathWithRoundedRect:buttonLast.bounds
                                                    byRoundingCorners:UIRectCornerTopRight | UIRectCornerBottomRight
                                                          cornerRadii:CGSizeMake(7, 7)];
    CAShapeLayer *maskLayer2 = [[CAShapeLayer alloc] init];
    maskLayer2.frame = buttonLast.bounds;
    maskLayer2.path = maskPath2.CGPath;
    buttonLast.layer.mask = maskLayer2;
    
    return backWrap;
}

- (void)setCenterNavSelectIndex:(NSInteger)index
{
    NSInteger tag = index;
    if (tag < 1) {
        return;
    }
    
    UIView *wrap = [_nav viewWithTag:7000];
    for (int i = 1; i <= wrap.subviews.count; i++) {
        UIButton *button = (UIButton *)[wrap viewWithTag:7000+i];
        if (tag == i) {
            [button setTitleColor:[UIUtils getColorByString:AppStyleConfig[appUserType][@"navColor"]] forState:UIControlStateNormal];
            [button setBackgroundColor:[UIColor whiteColor]];
        }else {
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [button setBackgroundColor:[UIUtils getColorByString:AppStyleConfig[appUserType][@"navColor"]]];
        }
    }
}

- (void)centerNavClick:(UIButton *)button
{
    NSInteger tag = button.tag - 7000;
    if (tag < 1) {
        return;
    }
    
    UIView *wrap = [_nav viewWithTag:7000];
    for (int i = 1; i <= wrap.subviews.count; i++) {
        UIButton *button = (UIButton *)[wrap viewWithTag:7000+i];
        if (tag == i) {
            [button setTitleColor:[UIUtils getColorByString:AppStyleConfig[appUserType][@"navColor"]] forState:UIControlStateNormal];
            [button setBackgroundColor:[UIColor whiteColor]];
        }else {
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [button setBackgroundColor:[UIUtils getColorByString:AppStyleConfig[appUserType][@"navColor"]]];
        }
    }
    
    if (_centerNavBlock) {
        _centerNavBlock(tag);
    }
}

#pragma mark - Public Method

-(BOOL)isIncludeSpecialCharact: (NSString *)str {
  //***需要过滤的特殊字符：~￥#&*<>《》()[]{}【】^@/￡¤￥|§¨「」『』￠￢￣~@#￥&*（）——+|《》$_€。
  NSRange urgentRange = [str rangeOfCharacterFromSet: [NSCharacterSet characterSetWithCharactersInString: @"<>,'\""]];
  if (urgentRange.location == NSNotFound)
  {
    return NO;
  }
  return YES;
}

//判断是否为直辖市
- (BOOL)isMunicipalityCity:(NSString *)cityName
{
    NSArray *municipalityCities = @[@"北京",@"上海",@"天津",@"重庆"];
    if ([municipalityCities containsObject:cityName]) {
        return YES;
    }
    return NO;
}

//获取当前时间戳
- (NSInteger)getTimeStamp
{
    NSDate *fromdate = [NSDate date];
    NSInteger time = [fromdate timeIntervalSince1970];
    return time;
}

//获取今天日期
- (NSString *)getStringFromDate:(NSDate *)date
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *destDateString;
    if (date == nil) {
        destDateString = [dateFormatter stringFromDate:[NSDate date]];
    }else {
        destDateString = [dateFormatter stringFromDate:date];
    }
    
    return destDateString;
}

//去除字符串两端空格
- (NSString *)TrimStringSpace:(NSString *)str
{
    return [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}

#pragma mark - Tabbar

//请求tabbar消息
- (void)requestTabBarData:(BOOL)isTimeRestricted
{
    NSInteger now = [self getTimeStamp];
    NSInteger lastStamp = UDTabbarRequestStamp != nil ? [UDTabbarRequestStamp integerValue] : 0;
    NSInteger requestDuration = UDTabbarRequestDuration != nil ? [UDTabbarRequestDuration integerValue] : 1800;
    if (now < lastStamp + requestDuration && isTimeRestricted) {
        return;
    }
    
    [USER_DEFAULT setObject:[NSNumber numberWithInteger:now] forKey:UDTabbarRequestStampIdentify];
    [USER_DEFAULT synchronize];
    NSString *msgUrlString = [MessageURLString stringByAppendingString:@"&type=1"];
    [[AFAppClient sharedManager] getWithURL:msgUrlString
                             withParameters:@{@"version":[UIUtils appVersion]}
                                    success:^(NSDictionary *response){
                                        [self refreshTabBarData:response];
                                    }
                                    failure:nil];
}

- (void)refreshTabBarData:(NSDictionary *)result
{
    NSArray *tabbarData = result[@"data"];
    if (tabbarData == nil) {
        return;
    }
    if (result[@"time"]) {
        [USER_DEFAULT setObject:result[@"time"] forKey:UDTabbarRequestDurationIdentify];
    }
    for (NSDictionary *dic in tabbarData) {
        if ([[NSString stringWithFormat:@"%@", dic[@"fragment"]] isEqualToString:@"1"]) {
            [USER_DEFAULT setObject:dic[@"tips"] forKey:UDCountForHomeIdentify];
        }else if ([[NSString stringWithFormat:@"%@", dic[@"fragment"]] isEqualToString:@"2"]){
            NSDictionary *oldDic = [[NSDictionary alloc]initWithDictionary:UDFindOldIds];
            NSDictionary *newDic = dic[@"tips"];
            NSMutableDictionary *upDic = [[NSMutableDictionary alloc]init];
            NSMutableDictionary *desDic = [[NSMutableDictionary alloc]init];

            if ([oldDic count] <= 0) {
                for (NSString *key in [newDic allKeys]) {
                    [upDic setObject:@"1" forKey:key];
                    [desDic setObject:[NSString stringWithFormat:@"%@", [newDic objectForKey:key]] forKey:key];
                }
            }else {
                for (NSString *key in [newDic allKeys]) {
                    NSString *tip = [NSString stringWithFormat:@"%@", [oldDic objectForKey:key]];
                    if (![oldDic objectForKey:key]) {
                        [upDic setObject:@"1" forKey:key];
                    }else {
                        [upDic setObject:tip forKey:key];
                    }
                    [desDic setObject:[NSString stringWithFormat:@"%@", [newDic objectForKey:key]] forKey:key];
                }
            }

            [USER_DEFAULT setObject:upDic forKey:UDFindOldIdsIdentify];
            [USER_DEFAULT setObject:desDic forKey:UDFindNewIdsIdentify];
        }else if ([[NSString stringWithFormat:@"%@", dic[@"fragment"]] isEqualToString:@"3"]){
            if (!UDActivityOldId) {
                [USER_DEFAULT setObject:@0 forKey:UDActivityOldIdIdentify];
            }
            [USER_DEFAULT setObject:dic[@"tips"] forKey:UDActivityNewIdIdentify];
        }else if ([[NSString stringWithFormat:@"%@", dic[@"fragment"]] isEqualToString:@"4"]){            
            if (!UDMineOldId) {
                [USER_DEFAULT setObject:@1 forKey:UDMineOldIdIdentify];
            }
            [USER_DEFAULT setObject:@1 forKey:UDMineNewIdIdentify];
            //[USER_DEFAULT setObject:dic[@"tips"] forKey:UDMineNewIdIdentify];
        }
    }
    
    [USER_DEFAULT synchronize];
    [self refreshTabBar:TabbarTypeAll];
}

//uitabbar 更新呢小红点显示 99:all 0-4:对应的项目
- (void)refreshTabBar:(TabbarType)type
{
    AppDelegate *appDelegate = [self getAppDelegate];
    NSArray *items = [[appDelegate.tabBarController tabBar] items];
    
    //社区
    if ((type == TabbarTypeClub || type == TabbarTypeAll) && UDCountForHome) {
        NSInteger count = [UDCountForHome integerValue];
        UITabBarItem *item = (UITabBarItem *)items[0];
        NSString *unSelectedImage=@"tabbar_icon_1";
        NSString *selectedImage=@"tabbar_icon_1";
        if(appUserType==2){
            unSelectedImage=@"tabbar_icon_year_1";
            selectedImage=@"tabbar_icon_year_selected_1";
        }
        if (Current_device_vesion>=7.0) {
            if (count > 0) {
                item.image = [[self imageAddRedDot:unSelectedImage] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
                item.selectedImage = [[self imageAddRedDot:selectedImage] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
            }else {
                item.image = [[UIImage imageNamed:unSelectedImage] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
                item.selectedImage = [[UIImage imageNamed:selectedImage] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
            }
        }else{
            if (count > 0) {
                [item setFinishedSelectedImage:[self imageAddRedDot:selectedImage]
                   withFinishedUnselectedImage:[self imageAddRedDot:unSelectedImage]];
            }else {
                [item setFinishedSelectedImage:[UIImage imageNamed:selectedImage]
                   withFinishedUnselectedImage:[UIImage imageNamed:unSelectedImage]];
            }
        }
    }
    
    //发现
    if ((type == TabbarTypeFind || type == TabbarTypeAll) && UDFindNewIds) {
        NSInteger count = 0;
        NSDictionary *newDic = UDFindNewIds;
        NSDictionary *oldDic = UDFindOldIds;

        for (NSString *key in [newDic allKeys]) {
            NSInteger oldId = [[NSString stringWithFormat:@"%@",[oldDic objectForKey:key]] integerValue];
            NSInteger newId = [[NSString stringWithFormat:@"%@", [newDic objectForKey:key]] integerValue];
            if (newId > oldId) {
                count++;
            }
        }
        UITabBarItem *item = (UITabBarItem *)items[2];
        
        NSString *unSelectedImage=@"tabbar_icon_3";
        NSString *selectedImage=@"tabbar_icon_3";
        if(appUserType==2){
            unSelectedImage=@"tabbar_icon_year_3";
            selectedImage=@"tabbar_icon_year_selected_3";
        }
        
        if (Current_device_vesion>=7.0) {
            if (count > 0) {
                item.image = [[self imageAddRedDot:unSelectedImage] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
                item.selectedImage = [[self imageAddRedDot:selectedImage] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
            }else {
                item.image = [[UIImage imageNamed:unSelectedImage] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
                item.selectedImage = [[UIImage imageNamed:selectedImage] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
            }
        }else{
            if (count > 0) {
                [item setFinishedSelectedImage:[self imageAddRedDot:selectedImage]
                   withFinishedUnselectedImage:[self imageAddRedDot:unSelectedImage]];
            }else {
                [item setFinishedSelectedImage:[UIImage imageNamed:selectedImage]
                   withFinishedUnselectedImage:[UIImage imageNamed:unSelectedImage]];
            }
        }
    }
    
    //活动
    if ((type == TabbarTypeActivity || type == TabbarTypeAll) && UDActivityNewId) {
        NSInteger oldId = [UDActivityOldId integerValue];
        NSInteger newId = [UDActivityNewId integerValue];
        UITabBarItem *item = (UITabBarItem *)items[3];
        
        NSString *unSelectedImage=@"tabbar_icon_4";
        NSString *selectedImage=@"tabbar_icon_4";
        if(appUserType==2){
            unSelectedImage=@"tabbar_icon_year_4";
            selectedImage=@"tabbar_icon_year_selected_4";
        }
        
        if (Current_device_vesion>=7.0) {
            if (oldId < newId) {
                item.image = [[self imageAddRedDot:unSelectedImage] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
                item.selectedImage = [[self imageAddRedDot:selectedImage] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
            }else {
                item.image = [[UIImage imageNamed:unSelectedImage] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
                item.selectedImage = [[UIImage imageNamed:selectedImage] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
            }
        }else{
            if (oldId < newId) {
                [item setFinishedSelectedImage:[self imageAddRedDot:selectedImage]
                   withFinishedUnselectedImage:[self imageAddRedDot:unSelectedImage]];
            }else {
                [item setFinishedSelectedImage:[UIImage imageNamed:selectedImage]
                   withFinishedUnselectedImage:[UIImage imageNamed:unSelectedImage]];
            }
        }
    }
}

//给图片增加小红点
- (UIImage *)imageAddRedDot:(NSString*)imageName {
    
//    CGRect rect = CGRectMake(0, 0, (APP_SCREEN_WIDTH / 5), CUSTOM_TABBAR_HEIGHT);
    CGRect imageRect = CGRectMake(0, 0, 50, 30);
    UIGraphicsBeginImageContextWithOptions(imageRect.size, NO, 0.0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    
    UIImage *originalImage = [UIImage imageNamed:imageName];
    [originalImage drawInRect:imageRect];
    
    CGContextSetFillColorWithColor(context,[UIColor redColor].CGColor);
    CGRect dotRect = CGRectMake(38.0, 1.5, 6.5, 6.5);
    CGContextFillEllipseInRect (context, dotRect);
    CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0);
    CGContextStrokeEllipseInRect(context, dotRect);
    CGContextFillPath(context);
    
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return theImage;
}

- (void)changeTabbarStyleColor {
    
    [[self getAppDelegate] changeAppStyleColor];
    UIColor *color = [UIUtils getColorByString:AppStyleConfig[appUserType][@"tabbarColor"]];
    UIColor *selectedColor = [UIUtils getColorByString:AppStyleConfig[appUserType][@"tabbarSelectedColor"]];
    [self.tabBarController.tabBar setSelectionIndicatorImage:[UIImage imageWithColor:selectedColor size:CGSizeMake((APP_SCREEN_WIDTH / 5), CUSTOM_TABBAR_HEIGHT)]];
    if (Current_device_vesion >= 7.0) {
        [self.tabBarController.tabBar setBarTintColor:color];
    }
}

#pragma mark - Memory Manage
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
  [self setLoadingView:nil];
  [super viewDidUnload];
}
@end
